﻿// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";

    WinJS.Namespace.define("PdfShowcase", {
        zoomedInViewSource: null,
        zoomedOutViewSource: null
    });

    

    WinJS.UI.Pages.define("/pages/reportviewer/reportviewer.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            // TODO: Initialize the page here.
        },

        unload: function () {
            // TODO: Respond to navigations away from this page.
        },

        updateLayout: function (element) {
            /// <param name="element" domElement="true" />

            // TODO: Respond to changes in layout.
        }
    });
})();

var readBuffer;
var Buffer;
var dataSource = null;
var streamContent = null;
$(window).load(function ()
{
    initializeAppBar();

    var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
    printManager.onprinttaskrequested = onPrintTaskRequested;

    
    var uri = Windows.Foundation.Uri("ms-appx:///Images/ReportNation.pdf");
    Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(function (file) {
        Windows.Storage.FileIO.readBufferAsync(file).then(function (fileBuffer) {
            Buffer = fileBuffer;

            streamContent = new Windows.Storage.Streams.InMemoryRandomAccessStream();

            streamContent.writeAsync(fileBuffer).then(function (bytesWritten) {
                // Rewind the stream.
                streamContent.seek(0);
                loadPDF(streamContent);
                HideBusy('busy');
            })
        })
    });

})

function onPrintTaskRequested(printEvent) {
    var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
        args.setSource(MSApp.getHtmlPrintDocumentSource(document));

        // Register the handler for print task completion event
        //printTask.oncompleted = onPrintTaskCompleted;
    });
}

function readDataAsync(stream) {
    return stream.readAsync(readBuffer, readBuffer.capacity, Windows.Storage.Streams.InputStreamOptions.none).then(function (buffer) {
        // Continue reading until the response is complete.
        Buffer = buffer;
    });
}

function loadPDF(streamfile) {

    // Loading PDf file from the assets
    pdfLibrary.loadPDF(streamfile).done(function (pdfDocument) {

        if (pdfDocument !== null) {
            // Initialize ZoomedInView control of Semantic Zoom
            initializeZoomedInView(pdfDocument);

            // Initialize ZoomedOutView control of Semantic Zoom
            initializeZoomedOutView(pdfDocument);
        }
    }, function error() {
        // Password protected file, user should provide a password to open the file
    });
};

function initializeZoomedInView(pdfDocument) {

    // Virtualized Data Source takes following arguments
    //  zoomedInListView:           element for zoomed out view
    //  pdfDocument:                PDF document returned by loadPDF
    //  pdfPageRenderingOptions:    null, will be initialized by Virtualized Data Source Constructor
    //  pageToLoad:                 number of pages to load on each request to Virtualized Data source itemFromIndex method
    //  inMemoryFlag:               false, all images are kept in memory 
    //  temporary folder:           null, not required as inMemoryFlag is set to false

    if (PdfShowcase.zoomedInViewSource !== null) {

        // Unloading currently loaded PDF file
        PdfShowcase.zoomedInViewSource.unload();
    }

    var zoomedInListView = document.getElementById("zoomedInListView");

    // Initializing control
    zoomedInListView.winControl.itemDataSource = null;
    zoomedInListView.winControl.layout = new WinJS.UI.GridLayout();

    var zoomedInViewSource = new PDF.dataAdapter.dataSource(zoomedInListView, pdfDocument, null, 5, true, null);

    //  Setting data source for element
    zoomedInListView.winControl.itemDataSource = zoomedInViewSource;

    PdfShowcase.zoomedInViewSource = zoomedInViewSource;

};

function initializeZoomedOutView(pdfDocument) {

    if (PdfShowcase.zoomedOutViewSource !== null) {

        // Unloading currently loaded PDF file
        PdfShowcase.zoomedOutViewSource.unload();
    }

    // Initializing page rendering options for zoomed out view
    var pdfPageRenderingOptions = new Windows.Data.Pdf.PdfPageRenderOptions;

    // High contrast will be honored by PDF
    pdfPageRenderingOptions.isIgnoringHighContrast = false;

    // Setting the height of thumbnail to fixed value 300px. 
    // We have chosen 300px as the size of thumbnail as it gives decent preview of a PDF page on all resolutions
    pdfPageRenderingOptions.destinationHeight = 300;

    WinJS.Application.local.folder.createFolderAsync("temp", Windows.Storage.CreationCollisionOption.replaceExisting).done(function (tempFolder) {
        // Virtualized Data Source takes following arguments
        //  zoomedOutListView:          element for zoomed out view
        //  pdfDocument:                PDF document returned by loadPDF
        //  pdfPageRenderingOptions:    page rendering option with height set to 300px for Zoomed Out view
        //  pageToLoad:                 number of pages to load on each request to Virtualized Data source itemFromIndex method
        //  inMemoryFlag:               true,all the thumbnails generated will be placed on disk
        //  temporary folder:           path on disk where these images will be kept

        var zoomedOutListView = document.getElementById("zoomedOutListView");

        // Initializing control
        zoomedOutListView.winControl.itemDataSource = null;
        zoomedOutListView.winControl.layout = new WinJS.UI.GridLayout();

        var zoomedOutViewSource = new PDF.dataAdapter.dataSource(zoomedOutListView, pdfDocument, pdfPageRenderingOptions, 5, false, tempFolder);

        // Setting data source for element
        zoomedOutListView.winControl.itemDataSource = zoomedOutViewSource;

        PdfShowcase.zoomedOutViewSource = zoomedOutViewSource;
    });
};


// This function initializes app bar and its options
function initializeAppBar() {

    // Add event listeners to handle click of Open option in command bar
    document.getElementById("Close").addEventListener("click", closeClick, false);
    document.getElementById("Print").addEventListener("click", printClick, false);
}

function closeClick() {
    GoBack();
}

function printClick() {
    var appbar = document.body.querySelector('#appBar');
    if (!IsNullOrEmty(appbar))
        appbar.winControl.hide();

    ShowBusy('busy');

    Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync(GenarateIDWindow() + ".pdf", Windows.Storage.CreationCollisionOption.replaceExisting).done(
                 function (file) {
                     Windows.Storage.FileIO.writeBufferAsync(file, Buffer).done(
                      function () {
                          Windows.System.Launcher.launchFileAsync(file).done(
                             function (success) {
                                 // anything you want to do after default program launched        });
                             });
                          HideBusy('busy');
                      },
                      function (error) {
                          WinRT_ShowMessage(error);
                          HideBusy('busy');
                      });

                 },
                 function (error) {
                     WinRT_ShowMessage(error);
                     HideBusy('busy');
                 });
}

window.blobUriFromStream = WinJS.Binding.initializer(function (source, sourceProp, dest, destProp) {
    if (source[sourceProp] !== null) {
        dest[destProp] = URL.createObjectURL(source[sourceProp], { oneTimeOnly: true });
    }
});

window.zoomedInItem = window.zoomedOutItem = WinJS.UI.eventHandler(function (item) {
    var clone = Object.create(item);
    clone.groupIndexHint = clone.firstItemIndexHint = item.index;
    return clone;
});
